package com.lych.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.lych.autoconfig.template.OssTemplate;
import com.lych.commons.utils.Constants;
import com.lych.dubbo.api.CommentVideoApi;
import com.lych.dubbo.api.UserFocusApi;
import com.lych.dubbo.api.UserInfoApi;
import com.lych.dubbo.api.VideoApi;
import com.lych.model.domain.UserInfo;
import com.lych.model.enums.CommentType;
import com.lych.model.mongo.Comment;
import com.lych.model.mongo.CommentVideo;
import com.lych.model.mongo.FocusUser;
import com.lych.model.mongo.Video;
import com.lych.model.vo.CommentVo;
import com.lych.model.vo.ErrorResult;
import com.lych.model.vo.PageResult;
import com.lych.model.vo.VideoVo;
import com.lych.server.exception.BusinessException;
import com.lych.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.server.WebServer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideoService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserFocusApi userFocusApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private CommentVideoApi commentVideoApi;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 视频上传
     * @param videoThumbnail
     * @param videoFile
     */
    public void smallVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //封面图片上传到阿里云,获取地址
        String upload = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //视频上传到fast上，获取请求地址
        //获得文件的后缀名
        String filename = videoFile.getOriginalFilename();
        String sufix = filename.substring(filename.lastIndexOf(".") + 1);
        //文件输入流，文件长度，文件后缀，元数据
        StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), sufix, null);
        String videoUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        //创建video对象，设置属性
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(upload);
        video.setVideoUrl(videoUrl);
        video.setText("啦啦啦啦啦");
        //调用api保存
        Video video1 = videoApi.save(video);
        //保存日志
        mqMessageService.sendLogService(UserHolder.getUserId(),"0301","video",video1.getId().toString());
    }

    /**
     * 小视频列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult pageSmallVideos(Integer page, Integer pagesize) {
        //调用api查询视频数据并分页
        List<Video> list = videoApi.findAll(page,pagesize);
        //封装成vo对象
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo userInfo = userInfoApi.findById(video.getUserId());
            if (userInfo != null) {
                VideoVo vo = VideoVo.init(userInfo,video);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    /**
     * 视频用户关注
     * @param followUserId
     */
    public void userFocus(Long followUserId) {
        //查询当前用户id
        Long userId = UserHolder.getUserId();
        //构建对象，调用api保存
        FocusUser focusUser = new FocusUser();
        focusUser.setFollowUserId(followUserId);
        focusUser.setUserId(userId);
        focusUser.setCreated(System.currentTimeMillis());
        userFocusApi.save(focusUser);
        //拼接key，将关注信息存入redis
        String key = Constants.FOCUS_USER+followUserId;
        String hashKey = Constants.FOCUS_USER+userId;
        redisTemplate.opsForHash().put(key,hashKey,"1");
    }

    /**
     * 视频用户关注 - 取消
     * @param followUserId
     */
    public void userUnFocus(Long followUserId) {
        //查询当前用户id
        Long userId = UserHolder.getUserId();
        //调用api删除
        userFocusApi.delete(userId,followUserId);
        //拼接key，将关注信息在redis中删除
        String key = Constants.FOCUS_USER+followUserId;
        String hashKey = Constants.FOCUS_USER+userId;
        redisTemplate.opsForHash().delete(key,hashKey);

    }

    /**
     * 视频点赞
     * @param id
     */
    public void idLike(String id) {
        //查询操作用户id
        Long userId = UserHolder.getUserId();
        String key = Constants.VIDEO_LIKE_HASHKEY + id;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + userId;
        //判断是否点赞
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (!StringUtils.isEmpty(value)) {
            //点赞了，抛出异常
            throw new BusinessException(ErrorResult.likeError());
        }
        //进行点赞
        videoApi.idLike(id,userId);
        //将数据存入redis
        redisTemplate.opsForHash().put(key,hashKey,"1");
        //保存日志
        mqMessageService.sendLogService(userId,"0302","video",id);
    }

    /**
     * 视频点赞 - 取消
     * @param id
     */
    public void dislike(String id) {
        //查询操作用户id
        Long userId = UserHolder.getUserId();
        String key = Constants.VIDEO_LIKE_HASHKEY + id;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + userId;
        //查看是否点赞
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (StringUtils.isEmpty(value)) {
            //没点赞，抛出异常
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //取消点赞
        videoApi.dislike(id,userId);
        //删除redis中的数据
        redisTemplate.opsForHash().delete(key,hashKey);
        //保存日志
        mqMessageService.sendLogService(userId,"0303","video",id);
    }

    /**
     * 评论列表分页查询
     * @param id
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult idComments(String id, Integer page, Integer pagesize) {
        //调用api分页查询视频评论列表
        List<CommentVideo> list = commentVideoApi.idComments(id,page,pagesize);
        int size = list.size();
        //非空判断
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //拿到评论用户的id
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(ids, null);
        //构造返回对象
        List<CommentVo> vos = new ArrayList<>();
        for (CommentVideo commentVideo : list) {
            UserInfo userInfo = infoMap.get(commentVideo.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.initVideo(userInfo,commentVideo);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,size,vos);
    }

    /**
     * 评论发布
     * @param id
     * @param comment
     */
    public void findComments(String id, String comment) {
        //获得当前评论人的id
        Long userId = UserHolder.getUserId();
        //构造Comment
        CommentVideo comment1 = new CommentVideo();
        comment1.setContent(comment);
        comment1.setCreated(System.currentTimeMillis());
        comment1.setUserId(userId);
        comment1.setPublishId(new ObjectId(id));
        //调用api保存
        commentVideoApi.save(comment1);
        //保存日志
        mqMessageService.sendLogService(userId,"0304","video",id);


    }

    /**
     * 评论点赞
     * @param publishId
     */
    public void commentsIdLike(String publishId) {
        String key = Constants.VIDEO_INTERACT_KEY + publishId;
        String hashKey = Constants.VIDEO_INTERACT_KEY + UserHolder.getUserId();
        //调用redis查看是否已经点赞
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(key,hashKey);
        //如果已经点赞，抛异常
        if (aBoolean) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //调用api，添加点赞数量
        commentVideoApi.commentsIdLike(publishId);
        //拼接key，将点赞数据存入redis
        redisTemplate.opsForHash().put(key,hashKey,"1");
    }

    /**
     * 评论点赞 - 取消
     * @param publishId
     */
    public void commentsIdDislike(String publishId) {
        String key = Constants.VIDEO_INTERACT_KEY + publishId;
        String hashKey = Constants.VIDEO_INTERACT_KEY + UserHolder.getUserId();
        //调用redis查看是否已经点赞
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(key,hashKey);
        //如果没有点赞，抛异常
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //调用api删除点赞数据
        commentVideoApi.commentsIdDislike(publishId);
        //删除redis中的数据
        redisTemplate.opsForHash().delete(key,hashKey);
    }
}
